package chat

import (
	"bigmodel/service/chat/baidu"
	"context"
	"errors"
	"net/http"

	"github.com/swxctx/xlog"
)


type Baidu struct {
	cli *baidu.Client
}

// NewClient 初始化百度请求客户端s
func NewBaidu(apiKey, secretKey string, debug ...bool) (*Baidu,error) {
	client,err := baidu.MustNewClient(apiKey, secretKey, debug...)
	if err != nil {
		return nil,err
	}
	bd := &Baidu{
		cli: client,
	}
	return bd,nil
}

func MustNewBaidu(apiKey, secretKey string, debug ...bool) (*Baidu,error) {
	bd,err := NewBaidu(apiKey, secretKey,debug ...)
	return bd,err
}

func (bd *Baidu)Chat(ctx context.Context, resw http.ResponseWriter, args *ChatDoArgsV1,conf string) (*ChatDoResultV1, error){
	model := args.Model
	creq := &baidu.ChatRequest{
		Messages: []baidu.MessageInfo{
			{
				Role: baidu.CHAT_MESSAGE_ROLE_USER,
				Content: args.Content,
			},
		},
		Temperature: float32(args.Temperature),
		MaxOutputTokens: int64(args.MaxTokens),
	}
	if !args.Stream {
		resp,err := bd.cli.Chat(model,creq)
		if err != nil {
			return nil,err
		}
		return &ChatDoResultV1{
			Message: resp.Result,
		},nil
	}
	streamReader,err := bd.cli.ChatStream(model,creq)
	if err != nil {
		return nil,err
	}
	defer streamReader.Close()

	f,ok := resw.(http.Flusher)
	if !ok {
		return nil,errors.New("flusher初始化错误")
	}
	// 读取流处理
	for {
		line, err := streamReader.Receive()
		if err != nil {
			xlog.Errorf("err-> %v", err)
			break
		}
		if streamReader.IsFinish() {
			xlog.Infof("read finish...")
			break
		}
		if streamReader.IsMaxEmptyLimit() {
			xlog.Errorf("read empty limir...")
			break
		}

		if len(line) == 0 {
			continue
		}
		resw.Write(streamResponse(string(line)))
		f.Flush()
	}
	return &ChatDoResultV1{
		Message: STREAM_DONE_FLAG,
	},nil
}